package com.code.family.controller;

import com.code.family.entity.pojo.Weather;
import com.code.family.utils.ResultVo;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import kong.unirest.UnirestException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 系统工具类操作接口
 * @author 上玄
 **/
@RestController
@RequestMapping("/api/utils")
public class UtilsController {

    /**
     * 获取今日天气
     */
    @GetMapping("/weatherToday")
    public ResultVo weatherToday() {
        // 设置请求URL
        String requestUrl = "https://api.suyanw.cn/api/qqtq.php?msg=重庆";

        String weather;
        try {
            // 发送GET请求并获取响应
            HttpResponse<String> response = Unirest.get(requestUrl)
                    .asString();

            // 输出响应状态码和内容
            System.out.println(response.getBody());
            weather = response.getBody();
            // 截取json数据
            // 匹配城市名称的正则表达式
            Pattern cityPattern = Pattern.compile("城市：(\\S+)");
            Matcher cityMatcher = cityPattern.matcher(weather);
            String city = null;
            if (cityMatcher.find()) {
                city = cityMatcher.group(1);
                System.out.println("城市: " + city);
            }

            // 匹配气温最低和最高的正则表达式
            Pattern tempPattern = Pattern.compile("气温：(\\d+)℃/(\\d+)℃");
            Matcher tempMatcher = tempPattern.matcher(weather);
            String maxTemp = null;
            String minTemp = null;
            if (tempMatcher.find()) {
                minTemp = tempMatcher.group(1);
                maxTemp = tempMatcher.group(2);
                System.out.println("最低气温: " + minTemp + "℃");
                System.out.println("最高气温: " + maxTemp + "℃");
            }
            // 封装进一个新的Weather对象
            Weather weatherObj = new Weather();
            weatherObj.setCity(city);
            weatherObj.setMaxTemp(maxTemp);
            weatherObj.setMinTemp(minTemp);
            weatherObj.setData(weather);
            return ResultVo.success(weatherObj);
        } catch (UnirestException e) {
            return ResultVo.error("获取天气信息失败");
        }
    }

    /**
     * 获取一句一言
     */
    @GetMapping("/getWords")
    public ResultVo getWords() {
        String requestUrl = "https://api.suyanw.cn/api/yiyan.php?type=txt";

        try {
            // 发送GET请求并获取响应
            HttpResponse<String> response = Unirest.get(requestUrl)
                    .asString();

            System.out.println(response.getBody());
            String words = response.getBody();
            // 解析json数据

            return ResultVo.success("请求成功",words);
        } catch (UnirestException e) {
            return ResultVo.error("获取一句话失败");
        }
    }


}